/**
 * Author:yuiop
 * Date:2022/3/11 14:17
 */
package com.devops.admin.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HuHttpUtil {
    public static JSONObject dealHttpAndResponse(String url) {
        return dealHttpAndResponse(url,null);
    }
    public static JSONObject dealHttpAndResponse(String url, Map<String,Object> paramMap) {
        return dealHttpAndResponse(Method.GET,url,paramMap);
    }
    public static JSONObject dealHttpAndResponse(Method type,String url,Map<String,Object> paramMap) {
        return dealHttpAndResponse(type,url,paramMap,null);
    }

    public static JSONObject dealHttpAndResponse(Method type,String url,String body) {
        return dealHttpAndResponse(type,url,null,body);
    }

    public static JSONObject dealHttpAndResponse(Method type,String url,Map<String,Object> paramMap,String body) {

        String response = "{\"code\":1}";
        if (type == Method.POST) {
            if (CollectionUtils.isNotEmpty(paramMap)) {
                response = HttpUtil.post(url,paramMap);
            } else {
                response = HttpUtil.post(url,body);
            }
        } else if (type == Method.DELETE || type == Method.PUT) {
            response = HttpUtil.createRequest(type,url).body(body).timeout(30000).execute().body();
        } else if (type == Method.GET)  {
            response = HttpUtil.get(url,paramMap);
        }
        try {
            return JSONUtil.parseObj(response);
        }catch (Exception e){
            e.printStackTrace();
            return JSONUtil.parseObj("{\"code\":1}");
        }
    }

    /**
     * @Author heyabo
     * @Description 发送表单请求上传文件
     * @Date 13:53 2022/4/13
     * @Param [repoName, file, url]
     * @return cn.hutool.json.JSONObject
     **/
    public static JSONObject upload(String repoName, MultipartFile file, String url){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String msg = "";
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setConnectionRequestTimeout(1000)
                    .setSocketTimeout(5000).build());
            File files = File.createTempFile(file.getName(),".tgz");
            file.transferTo(files);
            // 把文件转换成流对象FileBody
            FileBody bin = new FileBody(files);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    // 相当于<input type="file" name="file"/>
                    .addPart("chart", bin)
                    .addTextBody("repoName",repoName)
                    .build();

            httpPost.setEntity(reqEntity);

            // 发起请求 并返回请求的响应
            response = httpClient.execute(httpPost);
            // 获取响应对象
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                msg = EntityUtils.toString(resEntity, StandardCharsets.UTF_8);
            }
            // 销毁
            EntityUtils.consume(resEntity);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(response != null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if(httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (StrUtil.isNotBlank(msg)){
            return JSONUtil.parseObj(msg);
        }
        return null;
    }

    /**
     * 信任SSL证书
     * @return
     */
    public static CloseableHttpClient buildDefaultHttpClientTrustSSL(){
        SSLContext sslContext = null;
        try {
            sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestConfig config = RequestConfig.custom()
                .setSocketTimeout(30000)
                .setConnectTimeout(30000)
                .setConnectionRequestTimeout(30000)
                .setContentCompressionEnabled(true)
                .build();
        return HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
    }

    public static CloseableHttpClient buildDefaultHttpClient(){
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)
                .setConnectTimeout(30000)
                .setConnectionRequestTimeout(30000)
                .setContentCompressionEnabled(true)
                .setStaleConnectionCheckEnabled(true)
                .build();

        return HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
    }
}
